# 文档内容：标题、段落、文字块、图片和表格添加
# 标题添加： add_heading("标题名称"、level=标题等级)
# 段落添加: add_paragraph("段落文字内容")
# 文字块添加： 段落对象.add_run("文字内容")
# 添加图片： add_picture("图片地址"[,width=宽度,height=高度])
# 添加表格：add_table(rows=行数,cols=列数,表格形式)
# 文字块对象.add_break() 换行  add_page_break() 添加分页

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm

doc = Document()


# doc.add_heading("标题0",0)
# doc.add_heading("标题1------1111",1)
# doc.add_heading("标题2",2)
# doc.add_heading("标题3",3)
# doc.save('标题.docx')

# paragraph = doc.add_paragraph("段落文字内容")
# paragraph.add_run('测试111')
# paragraph.add_run('测试222')
# paragraph.add_run('测试333').add_break()
# paragraph.add_run('测试444')
# doc.save('段落和文字块.docx')


# doc.add_picture('rose.jpeg',width=Cm(13), height=Cm(9))
# doc.save('图片.docx')

def set_cell_border(cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        left={"sz": 24, "val": "dashed", "shadow": "true"},
        right={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))


list1 = [
    ["姓名", "性别", "家庭地址"],
    ["李雷", "男", "湖北省"],
    ["韩梅梅", "女", "北京市"],
    ["夏洛特", "男", "广东省"],
    ["马冬梅", "女", "湖南省"]
]

table = doc.add_table(rows=5, cols=3)
for row in range(len(list1)):
    cells = table.rows[row].cells
    for col in range(len(list1[0])):
        cells[col].text = str(list1[row][col])
        set_cell_border(cells[col],
                        top={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
                        bottom={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
                        left={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"},
                        right={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"})
doc.save('表格.docx')
